package com.pansoft.openplanet.blockchain;

import android.content.Context;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.pansoft.openplanet.blockchain.api.EosChainInfo;
import com.pansoft.openplanet.blockchain.bean.JsonToBeanResultBean;
import com.pansoft.openplanet.blockchain.chain.Action;
import com.pansoft.openplanet.blockchain.chain.SignedTransaction;
import com.pansoft.openplanet.blockchain.util.GsonEosTypeAdapterFactory;
import com.pansoft.openplanet.constant.IPAssetsConstant;

import java.math.BigDecimal;
import java.util.ArrayList;

/**
 * Created by pocketEos on 2018/5/2.
 * eosX适配
 */

public class EosDataManger {


    static String EOSCONTRACT = IPAssetsConstant.EOSCONTRACT;
    static String OCTCONTRACT = IPAssetsConstant.OCTCONTRACT;//erctoken
    static String ACTIONTRANSFER = IPAssetsConstant.ACTIONTRANSFER;
    static String PERMISSONION = IPAssetsConstant.PERMISSONION;

    Context mContext;
    EosChainInfo mChainInfoBean = new EosChainInfo();
    JsonToBeanResultBean mJsonToBeanResultBean = new JsonToBeanResultBean();
    String[] permissions;
    SignedTransaction txnBeforeSign;
    Gson mGson = new GsonBuilder()
            .registerTypeAdapterFactory(new GsonEosTypeAdapterFactory())
            .excludeFieldsWithoutExposeAnnotation().create();

    String contract, action, message, userpassword;
    int type = 1; //0即为红包 ， 1为转账
    String redpacketNumber = null;
    BigDecimal coinRate;//资产汇率

    public EosDataManger(Context context, String password) {
        mContext = context;
        this.userpassword = password;
    }


//    public void pushAction(String message, String permissionAccount) {
//        this.message = message;
//        if (message.contains("EOS")) {
//            this.contract = EOSCONTRACT;
//        } else {
//            this.contract = OCTCONTRACT;
//        }
//        this.action = ACTIONTRANSFER;
//        this.type = 1;
//        permissions = new String[]{permissionAccount + "@" + PERMISSONION};
//        getChainInfo();
//    }
//
//    public void getChainInfo() {
//        HttpUtils.getRequets(BaseUrl.HTTP_get_chain_info, this, new HashMap<String, String>(), new JsonCallback<ResponseBean>() {
//            @Override
//            public void onSuccess(Response<ResponseBean> response) {
//                if (response.body().code == 0) {
//                    mChainInfoBean = (EosChainInfo) JsonUtil.parseStringToBean(mGson.toJson(response.body().data), EosChainInfo.class);
//                    getabi_json_to_bin();
//                } else {
//                    LoadingDataUtilBlack.dismiss();
//                    ToastUtil.showToast(mContext, response.body().message);
//                }
//            }
//        });
//    }

    public void getabi_json_to_bin() {

//        JsonToBinRequest jsonToBinRequest = new JsonToBinRequest(contract, action, message.replaceAll("\\r|\\n", ""));
//        HttpUtils.postRequest(BaseUrl.HTTP_get_abi_json_to_bin, this, mGson.toJson(jsonToBinRequest), new JsonCallback<ResponseBean>() {
//            @Override
//            public void onSuccess(Response<ResponseBean> response) {
//                if (response.body().code == 0) {
//                    mJsonToBeanResultBean = (JsonToBeanResultBean) JsonUtil.parseStringToBean(mGson.toJson(response.body().data), JsonToBeanResultBean.class);
//                    txnBeforeSign = createTransaction(contract, action, mJsonToBeanResultBean.getBinargs(),
//                            permissions, mChainInfoBean);
//                    //扫描钱包列出所有可用账号的公钥
//                    List<String> pubKey = EosPublicAndPrivateKeyUtils.getActivePublicKey();
//                    getRequreKey(new GetRequiredKeys(txnBeforeSign, pubKey));
//                } else {
//                    LoadingDataUtilBlack.dismiss();
//                    ToastUtil.showToast(mContext, response.body().message);
//                    //ToastUtils.showLongToast(response.body().message);
//                }
//            }
//        });
    }

    /**
     * 生成新建账户的transaction
     * @param contract 合约名 eosio
     * @param actionName action名 newaccount
     * @param dataAsHex newaccount data
     * @param buyramData buyram data
     * @param delegatebwData delegate data
     * @param permissions 当前账户@active
     * @param chainInfo chainIInfo
     * @return
     */
    public SignedTransaction createNewAccountTransaction(String contract, String actionName, String dataAsHex,
                                                String buyramData, String delegatebwData,
                                                String[] permissions, EosChainInfo chainInfo) {

        Action action = new Action(contract, actionName);
        action.setAuthorization(permissions);
        action.setData(dataAsHex);

        Action buyram = new Action(contract, "buyrambytes");
        buyram.setAuthorization(permissions);
        buyram.setData(buyramData);

        Action delegatebw = new Action(contract, "delegatebw");
        delegatebw.setAuthorization(permissions);
        delegatebw.setData(delegatebwData);

        SignedTransaction txn = new SignedTransaction();
        txn.addAction(action);
        txn.addAction(buyram);
        txn.addAction(delegatebw);
        txn.putSignatures(new ArrayList<String>());


        if (null != chainInfo) {
            txn.setReferenceBlock(chainInfo.getHeadBlockId());
            txn.setExpiration(chainInfo.getTimeAfterHeadBlockTime(30000));
        }
        return txn;
    }

    /**
     * 生成转账的transaction
     * @param contract 合约名 eosio.token
     * @param actionName action名 transfer
     * @param dataAsHex newaccount data
     * @param permissions 当前账户@active
     * @param chainInfo chainIInfo
     * @return
     */
    public SignedTransaction createTransferTransaction(String contract, String actionName, String dataAsHex,
                                                String[] permissions, EosChainInfo chainInfo) {

        Action action = new Action(contract, actionName);
        action.setAuthorization(permissions);
        action.setData(dataAsHex);


        SignedTransaction txn = new SignedTransaction();
        txn.addAction(action);
        txn.putSignatures(new ArrayList<String>());


        if (null != chainInfo) {
            txn.setReferenceBlock(chainInfo.getHeadBlockId());
            txn.setExpiration(chainInfo.getTimeAfterHeadBlockTime(30000));
        }
        return txn;
    }

//    public void getRequreKey(GetRequiredKeys getRequiredKeys) {
//
//        HttpUtils.postRequest(BaseUrl.HTTP_get_required_keys, this, mGson.toJson(getRequiredKeys), new JsonCallback<ResponseBean>() {
//            @Override
//            public void onSuccess(Response<ResponseBean> response) {
//                if (response.body().code == 0) {
//                    RequreKeyResult requreKeyResult = (RequreKeyResult) JsonUtil.parseStringToBean(mGson.toJson(response.body().data), RequreKeyResult.class);
//                    EosPrivateKey eosPrivateKey = new EosPrivateKey(EosPublicAndPrivateKeyUtils.getPrivateKey(requreKeyResult.getRequired_keys().get(0), userpassword));
//                    txnBeforeSign.sign(eosPrivateKey, new TypeChainId(mChainInfoBean.getChain_id()));
//                    pushTransactionRetJson(new PackedTransaction(txnBeforeSign));
//                } else {
//                    LoadingDataUtilBlack.dismiss();
//                    ToastUtil.showToast(mContext, response.body().message);
//                }
//            }
//        });
//
//    }

//    public void pushTransactionRetJson(PackedTransaction body) {
//        HttpUtils.postRequest(BaseUrl.HTTP_push_transaction, this, mGson.toJson(body), new JsonCallback<ResponseBean>() {
//            @Override
//            public void onSuccess(final Response<ResponseBean> response) {
//
//                if (response.body().code == 0) {
//                    PushSuccessBean.DataBeanX dataBeanX = (PushSuccessBean.DataBeanX) JsonUtil.parseStringToBean(mGson.toJson(response.body().data), PushSuccessBean.DataBeanX.class);
//                    final Bundle bundle = new Bundle();
//                    if (type == 1) {
//                        LoadingDataUtilBlack.dismiss();
//                        ToastUtils.showShort(R.string.open_planet_transfer_success);
//
//                    }
//                } else {
//                    ToastUtil.showToast(AppContext.getInstance(), response.body().message);
//                }
//            }
//        });
//    }


    public EosDataManger setCoinRate(BigDecimal coinRate) {
        this.coinRate = coinRate;
        return this;
    }
}
